package com.example.myapplication;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.telecom.Call;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;


public class MainActivity extends AppCompatActivity {
    private ImageView imageView,topImage,bottomImage,enlargeImage;
    private Uri imageUri;
    private SharedPreferences mSp;
    private ScrollView scroll;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //        沉浸式阅读
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    |View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 实现透明状态栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        scroll = (ScrollView)findViewById(R.id.scroll);
        imageView = (ImageView)findViewById(R.id.image);
        enlargeImage = (ImageView)findViewById(R.id.enlargeImage);
        topImage = (ImageView)findViewById(R.id.topImage);
        bottomImage = (ImageView)findViewById(R.id.bottomImage);

        scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                int scrollY = view.getScrollY();
                System.out.println(scrollY);
                System.out.println(i);
                System.out.println(i1);
                System.out.println(i2);
                System.out.println(i3);
//                enlargeImage.setVisibility(View.VISIBLE);
                if(scrollY>=50){

                    Animation animation = AnimationUtils.loadAnimation(MainActivity.this,R.anim.enlarge);

                    animation.setFillAfter(true);


                    enlargeImage.startAnimation(animation);
                }
                if(scrollY > 100){
                    bottomImage.setImageResource(R.drawable.bottom_change);
                }
            }
        });

//        imageView.setImageResource(R.drawable.imgs);

        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                pickFile(1);
                return true;
            }
        });

        topImage.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                pickFile(2);
                return false;
            }
        });

        bottomImage.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                pickFile(3);
                return false;
            }
        });


        mSp = MainActivity.this.getSharedPreferences("mainPageImage1", Context.MODE_PRIVATE);
        mSp = MainActivity.this.getSharedPreferences("mainPageImage2", Context.MODE_PRIVATE);
        mSp = MainActivity.this.getSharedPreferences("mainPageImage3", Context.MODE_PRIVATE);

        String imageInfo1 = readInfo("mainPageImage1");
        String imageInfo2 = readInfo("mainPageImage2");
        String imageInfo3 = readInfo("mainPageImage3");
//        System.out.println(imageInfo+"_________71");

        if(imageInfo1!=null && imageInfo1!=""){
            imageView.setImageBitmap(new BitmapAndString().stringToBitmap(imageInfo1));
        }
        if(imageInfo2!=null && imageInfo2!=""){
            topImage.setImageBitmap(new BitmapAndString().stringToBitmap(imageInfo2));
        }
        if(imageInfo3!=null && imageInfo3!=""){
            bottomImage.setImageBitmap(new BitmapAndString().stringToBitmap(imageInfo3));
        }



    }



    //存数据
    public void writeInfo(Bitmap bitmap,int num) {
        SharedPreferences.Editor editor=mSp.edit();
        editor.putString("mainPageImage"+num,new BitmapAndString().bitmapToString(bitmap));
//        editor.putString("name",mEt.getText().toString());
        editor.commit();
        //editor.apply();
//        Toast.makeText(this,bitmap+"存储数据成功",Toast.LENGTH_LONG).show();
    }
    //读数据
    public String readInfo(String stor) {
        if(mSp==null) return null;
//        String info1 = mSp.getString("mainPageImage1", null);
//        String info2 = mSp.getString("mainPageImage2", null);
        String info = mSp.getString(stor, null);
//        mShowText.setText(info);
        System.out.println(info);
//        Toast.makeText(this,info+"读取数据成功",Toast.LENGTH_LONG).show();
        return info;
    }


    // 打开系统的文件选择器
    public void pickFile(int num) {
//动态申请获取访问 读写磁盘的权限
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
        } else {
            //打开相册
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
            intent.setType("image/*");
            startActivityForResult(intent, num); // 打开相册
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 5:
                if (resultCode == RESULT_OK) {
                    try {
                        // 将拍摄的照片显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        imageView.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 1:
            case 2:
            case 3:
                if (resultCode == RESULT_OK) { // 判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data,requestCode);
                    } else {
                        // 4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data,requestCode);
                    }
                }

                break;
            default:
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data,int num) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        // 根据图片路径显示图片
        displayImage(imagePath,num);
    }

    /**
     * android 4.4以前的处理方式
     * @param data
     */
    private void handleImageBeforeKitKat(Intent data,int num) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath,num);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            System.out.println(cursor.moveToFirst()+"_______187");
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath,int num) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            System.out.println(bitmap+"________251");
            System.out.println(num);
            switch (num){
                case 1:
                    imageView.setImageBitmap(bitmap);
                    writeInfo(bitmap,num);
                    break;
                case 2:
                    topImage.setImageBitmap(bitmap);
                    writeInfo(bitmap,num);
                    break;
                case 3:
                    bottomImage.setImageBitmap(bitmap);
                    writeInfo(bitmap,num);
            }



        } else {
            Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show();
        }
    }

    public void downLoadPage(View v){
//        Toast.makeText(MainActivity.this,"正在下载",Toast.LENGTH_SHORT).show();
//        Intent intent = new Intent(MainActivity.this,DownLoadActivity.class);
////        startActivity(intent);
//        ActivityOptionsCompat transitionActivityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(this);
//        startActivity(intent, transitionActivityOptions.toBundle());

//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {

//                MainActivity.this.finish();
        Intent mainIntent = new Intent(MainActivity.this,   DownLoadActivity.class);
        MainActivity.this.startActivity(mainIntent);
        overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
        overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);

//            }
//        }, 0);

    }
}